package third.lib.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import third.lib.common.exception.ThirdException;
import third.lib.common.status.ThirdStatus;

import java.util.concurrent.TimeUnit;

@Component
public class RedisStrUtil {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */
    public void set(String key, String value) throws ThirdException {
        try {
            stringRedisTemplate.opsForValue().set(key, value);
        } catch (Exception e) {
            throw new ThirdException(ThirdStatus.REDIS);
        }
    }

    public void set(String key, String value, long time) throws ThirdException {
        try {
            if (time > 0) {
                stringRedisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
        } catch (Exception e) {
            throw new ThirdException(ThirdStatus.REDIS);
        }
    }

    /**
     * 删除缓存
     *
     * @param key 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) throws ThirdException {
        try {
            if (key != null && key.length > 0) {
                if (key.length == 1) {
                    stringRedisTemplate.delete(key[0]);
                } else {
                    stringRedisTemplate.delete(CollectionUtils.arrayToList(key));
                }
            }
        } catch (Exception e) {
            throw new ThirdException(ThirdStatus.REDIS);
        }
    }
    // ============================String=============================

    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */

    public String get(String key) throws ThirdException {
        try {
            return key == null ? null : stringRedisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            throw new ThirdException(ThirdStatus.REDIS);
        }
    }
}
